package com.qing.demo.netty.client;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.qing.demo.netty.util.MsgUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.SocketChannel;


/**
 * @author caozhipeng
 * @date 2025/7/25
 */
public class MyClientHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        SocketChannel socketChannel=(SocketChannel)ctx.channel();
        System.out.println("客户端链接报告开始！");
        System.out.println("客户端链接报告信息：本客户端链接到服务器。ChannelID="+socketChannel.id());
        System.out.println("客户端链接报告结束！");

        String msg = "通知服务端，客户端链接建立成功！"+ DateUtil.date();
        ctx.writeAndFlush(MsgUtil.buildMsg(socketChannel.id().toString(),msg));
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("断开链接");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
        cause.printStackTrace();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("msg类型："+msg.getClass());
        System.out.println("服务端回复信息："+ JSONUtil.toJsonStr(msg));
    }
}
